//
//  XTXHomepageViewController.m
//  xiaotianxin
//
//  Created by XYC on 2019/10/25.
//  Copyright © 2019 XYC. All rights reserved.
//

#import "XTXHomepageViewController.h"
#import "XTXHomeViewController.h"
#import <GTSDK/GeTuiSdk.h>
#import <UserNotifications/UserNotifications.h>


@interface XTXHomepageViewController ()<VTMagicViewDataSource, VTMagicViewDelegate, VTMagicReuseProtocol,GeTuiSdkDelegate, UNUserNotificationCenterDelegate>


@end
#define getuiId @"aXmgbYQFzdAPSurTiHvzi7"
#define getuiSecret @"G4nZHS5aS59n6LWMC7b047"
#define getuiKey @"1Liof6xI8o9xcqGWkVA3O4"

#define updateUserLocation @"/m/userapiv2/updateUserGeTuiCid"

@implementation XTXHomepageViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        UITabBarItem* tabItem = [[UITabBarItem alloc]init];
        tabItem.selectedImage =  [[UIImage imageNamed:@"首页on"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        tabItem.image = [[UIImage imageNamed:@"首页off"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        tabItem.title = @"交友";
        self.tabBarItem = tabItem;
        self.title = tabItem.title;
        [tabItem setTitleTextAttributes:@{NSForegroundColorAttributeName:rgbYanse1(0x82e0ff)} forState:UIControlStateNormal];
        [tabItem setTitleTextAttributes:@{NSForegroundColorAttributeName:rgbYanse1(0x5974ff)} forState:UIControlStateSelected];
        [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self ChushiHuaGetui];

    // Do any additional setup after loading the view.
    self.magicView.navigationColor = [UIColor whiteColor];
    self.magicView.sliderColor = rgbYanse1(0x5974ff);
    self.magicView.sliderHeight = 4.5;
    self.magicView.sliderWidth = 30.0;
    self.magicView.layoutStyle = VTLayoutStyleCenter;
    self.magicView.switchStyle = VTSwitchStyleDefault;
    self.magicView.navigationHeight = zhuangtaiDaohangGao;
    self.magicView.dataSource = self;
    self.magicView.delegate = self;
    self.magicView.itemWidth = 65.f;
    self.magicView.separatorHeight = 0;
    self.magicView.separatorColor = [UIColor whiteColor];
    [self.magicView reloadData];
    [self.magicView reloadDataToPage:1];
    UIView *sliderView = [[UIView alloc] init];
    sliderView.layer.cornerRadius = 2.2;
    [self.magicView setSliderView:sliderView];
}
-(void)shallowLoveupdateuserLocationWhistle
{
   
    
}



- (void)ChushiHuaGetui
{
    [GeTuiSdk setChannelId:@"GT-Channel"];
    [GeTuiSdk startSdkWithAppId:getuiId appKey:getuiKey appSecret:getuiSecret
                       delegate:self];
    [self registerRemoteNotification];
    [GeTuiSdk clearAllNotificationForNotificationBar];
}


/**
 注册远程通知
 */
- (void)registerRemoteNotification {
    
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"G_request authorization succeeded!");
            }
        }];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        
    } else {
        // Fallback on earlier versions
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
}


/**
 iOS 10: App在前台获取到通知
 
 @param center center description
 @param notification <#notification description#>
 @param completionHandler <#completionHandler description#>
 */
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler  API_AVAILABLE(ios(10.0)){
    
    NSLog(@"G_Notification:%@", notification.request.content.userInfo);
    
    // 根据APP需要，判断是否要提示用户Badge、Sound、Alert
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    }
}

- (void)GeTuiSdkDidAliasAction:(NSString *)action result:(BOOL)isSuccess sequenceNum:(NSString *)aSn error:(NSError *)aError {
    if ([kGtResponseBindType isEqualToString:action]) {
        NSLog(@"G_绑定结果 ：%@ !, sn : %@", isSuccess ? @"成功" : @"失败", aSn);
        if (!isSuccess) {
            NSLog(@"G_绑定失败原因: %@", aError);
        }
    } else if ([kGtResponseUnBindType isEqualToString:action]) {
        NSLog(@"G_解绑结果 ：%@ !, sn : %@", isSuccess ? @"成功" : @"失败", aSn);
        if (!isSuccess) {
            NSLog(@"G_解绑失败原因: %@", aError);
        }
    }
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    NSDictionary *userinfo = response.notification.request.content.userInfo;
    
    NSLog(@"G_didReceiveNotification：%@",userinfo);
    // [ GTSdk ]：将收到的APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:userinfo];
    completionHandler();
}
#pragma mark - GeTuiSdkDelegate

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    // [4-EXT-1]: 个推SDK已注册，返回clientId
    NSLog(@"\n>>[GTSdk RegisterClient]2:%@\n\n", clientId);
    [GeTuiSdk bindAlias:clientId andSequenceNum:nil];
    if (clientId!=nil) {
        [[NSUserDefaults standardUserDefaults] setObject:clientId forKey:@"getuiCid"];
        [self shallowLoveupdateuserLocationWhistle];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"GetuiCid" object:nil];
    }
}

/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    NSLog(@"G_\n>>[GTSdk error]:%@\n\n", [error localizedDescription]);
    
}

/** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    // [ GTSdk ]：汇报个推自定义事件(反馈透传消息)
    [GeTuiSdk sendFeedbackMessage:90001 andTaskId:taskId andMsgId:msgId];
    // 数据转换
    NSString *paloadMsg = nil;
    NSDictionary *dic1;
    if (payloadData) {
        paloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
        
//        dic1 = [XTXHudong JsonStringChangeDict:paloadMsg];
    }
  
}

/** SDK收到sendMessage消息回调 */
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
    // 发送上行消息结果反馈
    NSString *msg = [NSString stringWithFormat:@"sendmessage=%@,result=%d", messageId, result];
    NSLog(@"G_\n>>[GTSdk DidSendMessage]:%@\n\n", msg);
}

/** SDK运行状态通知 */
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
    // 通知SDK运行状态
    NSLog(@"G_\n>>[GTSdk SdkState]:%u\n\n", aStatus);
}

/** SDK设置推送模式回调 */
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
    if (error) {
        NSLog(@"G_\n>>[GTSdk SetModeOff Error]:%@\n\n", [error localizedDescription]);
        return;
    }
    
    NSLog(@"G_\n>>[GTSdk SetModeOff]:%@\n\n", isModeOff ? @"开启" : @"关闭");
}

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler  API_AVAILABLE(ios(10.0)){
    NSLog(@"G_didReceiveNotificationRequest");
    //    self.contentHandler = contentHandler;
    //    self.dissectionexpurgate = [request.content mutableCopy];
    //    //       APNs
    //    WeakSelf;
    //    [GeTuiExtSdk handelNotificationServiceRequest:request withComplete:^{
    //        // Modify the notification content here...
    //        weakSelf.dissectionexpurgate.title =[NSString stringWithFormat:@"%@ [modified]",weakSelf.dissectionexpurgate.title];
    //        weakSelf.contentHandler(weakSelf.dissectionexpurgate);
    //    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}


- (NSArray<NSString *> *)menuTitlesForMagicView:(VTMagicView *)magicView {
    return @[@"关注", @"推荐",@"活跃"];
}

- (UIButton *)magicView:(VTMagicView *)magicView menuItemAtIndex:(NSUInteger)itemIndex {
    static NSString *itemIdentifier = @"itemIdentifier";
    UIButton *menuButton = [magicView dequeueReusableItemWithIdentifier:itemIdentifier];
    if (!menuButton) {
        menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
        menuButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15];
        [menuButton setTitleColor:rgbYanse1(0x7d7d7d) forState:UIControlStateNormal];
        [menuButton setTitleColor:rgbYanse1(0x5974ff) forState:UIControlStateSelected];
        [menuButton setTitleEdgeInsets:UIEdgeInsetsMake(zhuangtaiGao+10, 10, 10, 10)];
    }
    return menuButton;
}

- (UIViewController *)magicView:(VTMagicView *)magicView viewControllerAtPage:(NSUInteger)pageIndex {
    XTXHomeViewController *fineViewContr = [magicView dequeueReusablePageWithIdentifier:NSStringFromClass(XTXHomeViewController.class)];
    fineViewContr = [[XTXHomeViewController alloc] init];
    fineViewContr.pageIndex = pageIndex;
    return fineViewContr;
}

- (void)magicView:(VTMagicView *)magicView viewDidAppear:(UIViewController *)viewController atPage:(NSUInteger)pageIndex {
    //NSLog(@"pageIndex:%ld viewDidAppear:%@", (long)pageIndex, viewController.view);
}




@end
